<?php

namespace Api\Controller;
use Common\Controller\FirstendController;
class ApiAuthController extends FirstendController
{
    /**
     * 微信登录
     */
    public function SingUpForWeChat()
    {
        if(IS_POST){
            $userModel  = D('User');
            //openid和access_token,code
            $wxopenid     = I('wxopenid');
            //$headimgurl   = I('headimgurl');
            $code=I('code');
            if (!$wxopenid||!$code)              
                $this->jsonReturn($this->getMsg('success', '403', '参数错误'));
            $result=M('user')->where(array('code'=>$code))->find();
            if(!$result)
              $this->jsonReturn($this->getMsg('success', '403', '邀请码错误'));                 
            $user = $userModel->where(['wxopenid' => $wxopenid])->find();
            if ($user) {
                $userInfo['user_id']  = $user['id'];
                $userInfo['wxopenid'] = $wxopenid;
                $userInfo['wxheadpic']= $user['wxheadpic'];
            } else {
                $wx_user=$this->get_wx_user();
                if($wx_user){
                    $wx_user['nickname'];
                    $wx_user['headimgurl'];
                    $wx_user['openid'];
                    $res = $userModel->add(['wxopenid' => $wx_user['openid'],'wxheadpic'=>$wx_user['headimgurl'],'username'=>$wx_user['nickname']]);
                    $userInfo['user_id']  = $res;
                    $userInfo['wxopenid'] = $wxopenid;
                    $userInfo['mobile']   = ''; 
                    //注册流程
                    M('recom_login_tendays')->add(array('user_id'=>$res,'threeday'=>3,'sevenday'=>7,'create_at'=>  time()));                    
                    $this->reg_pro($code,$res);
                }else
                    $this->jsonReturn($this->getMsg('success', '403', "微信授权失败"));
            }

            $signature = user_encrypt($userInfo);
            $this->jsonReturn($this->getMsg('success', '200', $signature));
        }

        $this->jsonReturn($this->getMsg('success','403','非法请求'));
    }
    /**
     * 手机号登录
     * @return string
     */
    public function SingUpForMobile()
    {
        if(IS_POST){
            $userModel  = D('User');

            $mobile     = I('mobile');
            $code       = I('code');
            $is_exists=M('user')->where(array('mobile'=>I('mobile')))->find();
            if($is_exists)
                $this->jsonReturn($this->getMsg('success', '403', '手机号已经被注册'));
//            if (!$mobile||!$code) 
//                $this->jsonReturn($this->getMsg('success', '403', '参数错误'));
//            $result=M('user')->where(array('code'=>$code))->find();
//            if(!$result)
//                $this->jsonReturn($this->getMsg('success', '403', '邀请码错误'));
            if (!$mobile) 
                $this->jsonReturn($this->getMsg('success', '403', '参数错误'));
            $user = $userModel->where(['mobile' => $mobile])->find();
            if ($user) {
                $userInfo['user_id']  = $user['id'];
                $userInfo['wxopenid'] = $user['wxopenid'];
                $userInfo['mobile']   = $mobile;
            } else {
                $res = $userModel->add(['mobile' => $mobile,'username'=>$mobile]);
                $userInfo['user_id']  = $res;
                $userInfo['wxopenid'] = '';
                $userInfo['mobile']   = $mobile;  
                //注册流程
                M('recom_login_tendays')->add(array('user_id'=>$res,'threeday'=>3,'sevenday'=>7,'create_at'=>  time())); 
                $this->reg_pro($code,$res);              
            }           
            $signature = user_encrypt($userInfo);
            $this->jsonReturn($this->getMsg('success', '200', $signature));
        }

        $this->jsonReturn($this->getMsg('success','403','非法请求'));
    }

    /**
     * 获取用户信息（对token进行解密的demo）
     */
    public function getUserInfo()
    {
        $signature = I('signature');
        if(!$signature){
            $this->jsonReturn($this->getMsg('success','403','非法请求'));
        }
        $signatureData = user_decrypt($signature);
        if(!$signatureData->user_id){
            $this->jsonReturn($this->getMsg('success','403','token 错误'));
        }

        if($signatureData->exp < time()){
            $this->jsonReturn($this->getMsg('success','403','token 过期'));
        }

        $userModel  = D('User');
        $user = $userModel->find($signatureData->user_id);
        $this->jsonReturn($this->getMsg('success','200',$user));
    }
    //注册红包
    protected function reg_pro($code,$res){
        $lx=[1,2,3,4];
        $lx_str=['新用户红包','普通会员返利','邀请奖励','vip返利'];           
        $zhuce=10;//注册立即获得10元红包进入余额
        $xrhongbao=200;//新人红包划入---年化利率本金池
        //$yinian=365;//返还天数
        //$unlogin=30;//未登录比例
        //$unlogin_30=5;
        $this->recommend($code, $res);
        //红包进入可提现余额中
        //M('recom_user')->add(array('tx_money'=>$zhuce,'user_id'=>$res));
        //生成recom_hongbao记录，--recom_account_log账户变动记录
        // M('recom_hongbao')->add(array('user_id'=>$res));
       // $log['user_id']=$res;
       // $log['account']=$zhuce;
       // $log['op']="登录注册";  
       // $log['create_at']=time();
      //  M('recom_account_log')->add($log);
        //注册红包-红包-作为本金进入-年化利率本金池---//年化利率本金池---本金变动记录
        M('recom_benjin')->add(array('user_id'=>$res,'benjin'=>$xrhongbao,'zhuce'=>$xrhongbao,'create_at'=>time(),'days'=>0));       
        M('recom_benjinch')->add(array('user_id'=>$res,'bj_add'=>$xrhongbao,'lx_add'=>$lx[0],'lx_str'=>$lx_str[0],'create_at'=>time()));
        //1元返利
        $this->fanlichi($res);
        //注册红包进入可提现余额,并做记录----
//        M('recom_user')->add(array('user_id'=>$res,'tx_money'=>$zhuce));
//        M('recom_account_log')->add(array('user_id'=>$res,'account'=>$zhuce,'op'=>'注册红包','create_at'=>time()));
    }
    //上级vip每天返利比例记录
    protected  function recommend($code,$user_id){//注册流程
        if(!$code) return ;
        $result=M('user')->where(array('code'=>$code))->find();
        //邀请码是否正确
        if($result){
            //生成推荐关系
            $insert['user_id']=$result['id'];
            $insert['recom_id']=$user_id;
            $insert['create_at']=time();
            $flag=M('recom')->add($insert);
            //每天返利百分比
//            if($flag){
//                $zhuce_date=10;//注册之后10天
//                $new_rate=90;//新用户注册10天内                    
//                $rate=215;//峰值
//                $yinian=365;
//                $gouwu=80;//购物5天内
//                $bili=5;//推荐注册一次比例+5
//                $cishu=5;//注册最大限次数
//                $lx=[1,2,3,4];
//                $lx_str=['新用户红包','普通会员返利','邀请奖励','vip返利'];
//                //普通用户--每天返利百分比，只含有注册
//                M('recom_userrate')->add(array('user_id'=>$user_id,'create_at'=>time(),'rate'=>$new_rate,'zhuce_days'=>$zhuce_date,'zhuce_percent'=>$new_rate));
//                //上级推荐vip--每天返利百分比
//                $vip_rate=M('recom_userrate')->where(array('user_id'=>$result['id']))->find();
//                if($vip_rate){
//                    if($vip_rate['zhuce_days']!=0)
//                        $rate+=$vip_rate['zhuce_percent'];//还在10天注册期内+90
//                    if($vip_rate['gouwu_days']!=0)
//                        $rate+=$vip_rate['gouwu_percent'];//还在首次购物期内+80
//                    //未购物没有+80
//                    $rate_add=($vip_rate['rate']+$bili)<$rate?$vip_rate['rate']+$bili:$rate;
//                    $invite_add=$vip_rate['invite_add']+$bili<$bili*$cishu?$vip_rate['invite_add']+$bili:$bili*$cishu;
//                    //上级推荐vip--每天返利百分比--记录写入
//                    M('recom_userrate')->where(array('user_id'=>$result['id']))->save(array('rate'=>$rate_add,'invite_add'=>$invite_add));
//                    //增加比例：add_rate--应该增加，real_add--实际增加--比例增加日志
//                    M('recom_userrate_re')->add(array('user_id'=>$result['id'],'op'=>'推荐增加','add_rate'=>$bili,'real_add'=>$rate_add-$vip_rate['rate'],'create_at'=>time()));
//                    return "success";
//                }
//            }
        }else
            return  "code error";             
    }
    protected function get_wx_user(){
        $urlquery['openid']=I('openid');       
        $urlquery['access_token']=I('access_token');
        $joinstr=http_build_query($urlquery);
        $url="https://api.weixin.qq.com/sns/userinfo?".$joinstr;
        $curl=  curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
        $curl_re=curl_exec($curl);
        curl_close($curl);
        if($curl_re){
            return json_decode($curl_re,true);
        }else 
            return false;
    }
    //要请注册1元返利
    protected function fanlichi($user_id){
        //上级vip获得返利，进入返利金池B
        $zhuce=1;
        $days=90;
        $fanli=$zhuce/$days;
        $vip=M('recom')->where(array('recom_id'=>$user_id))->find();
        if($vip){
            //上级推荐人--获得---邀请用户返利--计入返利池B
            $insert['user_id']=$vip['user_id'];
            $insert['jine']=$zhuce;
            $insert['leix']='邀请好友';
            $insert['leix_type']=0;
            $insert['yaoqing']=$zhuce; 
            $insert['create_at']=  time();
            $insert['day_fanli']=$fanli;
            $insert['left_fanli']=$zhuce;
            $insert['leix_zijinchi']='B';
            M('recom_fanlichi')->add($insert);
            $add['user_id']=$vip['user_id'];
            $add['jine']=1;
            $add['leix']='邀请好友奖励';
            $add['leix_type']=0;
            $add['create_at']=  time();
            $add['fanli_leix']='B';
            M('recom_fanli_change')->add($add);//返利池金额变动
        }
    }
}